<template>
  <div v-loading="loading" class="app-container">
    <scheduleHeader ref="scheduleHeader" :parent="currentObj" />
    <div style="padding-top:5px">
      <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:1px;" round @click="toDowndloadStoreUpc">导出门店UPC</el-button>
      <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;" round @click="toDowndload">导出清单</el-button>
      <el-button size="mini" type="warning" style="float:right;margin-bottom:5px;" round @click="toConfirm">终审</el-button>
      <el-button size="mini" type="danger" style="float:right;margin-bottom:5px;" round @click="toMultipleReject">驳回</el-button>
      <el-button size="mini" type="success" style="float:right;margin-bottom:5px;" round @click="toMultipleApproved">通过</el-button>
      <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;" round @click="toAnalysisAll">分析</el-button>
      <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;" round @click="toQuery">查询</el-button>
      <el-table
        ref="rule3Table"
        :data="data"
        :row-key="getRowKeys"
        stripe
        size="small"
        border
        style="width: 100%;"
        :header-cell-style="{ height: '0px', padding: '0px' }"
        :row-style="{height: '0px'}"
        :cell-style="{padding: '0px'}"
        :height="tableHeight"
        @row-click="rowClick"
        @sort-change="sortChange"
        @selection-change="handleSelectionChange"
        @header-dragend="colChange"
      >
        <el-table-column :reserve-selection="true" type="selection" align="center" width="55" />
        <el-table-column :show-overflow-tooltip="true" type="index" label="序号" fixed="left" :width="colWidths.index" />
        <el-table-column :show-overflow-tooltip="true" label="采购ID" prop="buyerId" :width="colWidths.buyerId" />
        <el-table-column :show-overflow-tooltip="true" label="已上传商品数" sortable prop="uploadCount" :width="colWidths.uploadCount" />
        <itemStatus ref="itemStatus" :parent="currentObj" />
        <el-table-column :show-overflow-tooltip="true" label="最后更新时间" sortable prop="updatedTime" :width="colWidths.updatedTime">
          <template slot-scope="scope">
            <span>{{ parseToString(scope.row.updatedTime, 'yyyy-MM-dd HH:mm:ss') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" prop="operation" align="left" fixed="right" width="285">
          <template slot-scope="scope">
            <div class="list-operation">
              <el-link size="mini" type="primary" @click="toView(scope.row)">
                <span style="font-size: 12px;">查看</span>
              </el-link>
              <el-divider direction="vertical" />
              <el-link size="mini" type="primary" @click="toAnalysis(scope.row)">
                <span style="font-size: 12px;">分析</span>
              </el-link>
              <span v-if="showAudit">
                <el-divider direction="vertical" />
                <el-link size="mini" type="primary" @click="toApproved(scope.row)">
                  <span style="font-size: 12px;color:green">通过</span>
                </el-link>
                <el-divider direction="vertical" />
                <el-link size="mini" type="primary" @click="toReject(scope.row)">
                  <span style="font-size: 12px;color:red;">驳回</span>
                </el-link>
                <el-divider direction="vertical" />
                <el-link size="mini" type="danger" @click="toDelete(scope.row)">
                  <span style="font-size: 12px;">删除</span>
                </el-link>
              </span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <!--<el-pagination
        :total="total"
        :current-page.sync="currentPage"
        style="margin-top: 8px;"
        layout="total, prev, pager, next, sizes"
        :page-size="size"
        @size-change="sizeChange"
        @current-change="pageChange"
      />-->
    </div>
    <auditList ref="auditList" :parent="currentObj" />
    <analysisList ref="analysisList" :parent="currentObj" />
  </div>
</template>
<script>
import scheduleHeader from '@/views/olm/item-list/schedule-header'
import analysisList from '@/views/olm/analysis/analysis-list'
import itemStatus from '@/views/olm/part/itemStatus'
import initData from '@/api/olm/initData'
import { parseToString } from '@/utils/datefromat'
import { getSelector } from '@/views/olm/item-list/js/edit.js'
import auditList from '@/views/olm/audit-list/audit-list'
import { showNameByValue } from '@/utils/selectUtil'
import { doDownload } from '@/api/olm/download'
import { approved, reject, confirm } from '@/api/olm/item-list'
import { deleteScheduleBuyer } from '@/api/olm/schedule'
import { Message } from 'element-ui'

export default {
  components: { auditList, scheduleHeader, analysisList, itemStatus },
  mixins: [initData],
  data() {
    return {
      loading: false,
      syncTime: [],
      ids: [],
      checkedRows: [],
      currentObj: this,
      tableHeight: window.innerHeight * 0.65
    }
  },
  computed: {
    showAudit: function() {
      var schedule = this.$refs.scheduleHeader.schedule
      if (schedule && schedule.dataStatus && schedule.dataStatus !== 2) {
        return true
      } else {
        return false
      }
    }
  },
  watch: {
    data: {
      handler(n, o) {
        this.$nextTick(() => {
          this.$refs.rule3Table.doLayout()
        })
      }
    }
  },
  created() {
    this.$nextTick(() => {
    })
  },
  methods: {
    parseToString,
    getSelector,
    showNameByValue,
    // 查询栏重置触发
    resetForm() {
      this.param = { }
    },
    // 列表多选框触发
    handleSelectionChange(val) {
      this.ids = []
      this.checkedRows = []
      val.forEach(item => {
        this.ids.push(item.id)
        this.checkedRows.push(item)
      })
    },
    // 翻页选择row的key值
    getRowKeys(row) {
      return row.id
    },
    beforeInit() {
      this.url = process.env.VUE_APP_BASE_API3 + '/olmList/queryAuditList'
      return true
    },
    rowClick(row) {
      this.$refs.rule3Table.clearSelection(this.multipleSelection)
      this.$refs.rule3Table.toggleRowSelection(row, true)
    },
    // 列表排序触发
    sortChange(val) {
      const sortCol = val.prop.replace(/([A-Z])/g, '_$1').toUpperCase()
      let sortType = ''
      if (val.order === 'descending') {
        sortType = ' DESC'
      } else if (val.order === 'ascending') {
        sortType = ' ASC'
      }
      this.param.sort = sortCol + sortType
      this.init()
    },
    // 查询
    toQuery() {
      this.$refs.rule3Table.clearSelection(this.multipleSelection)
      this.page = 0
      this.currentPage = 1
      this.init()
    },
    // 查看
    toView(entity) {
      const auditList = this.$refs.auditList
      auditList.title = '查看'
      auditList.currentOperate = 'VIEW'
      auditList.params.buyerId = entity.buyerId
      auditList.schedule = this.$refs.scheduleHeader.schedule
      auditList.params.scheduleId = auditList.schedule.id
      auditList.toQuery()
      auditList.dialog = true
      console.log('toView')
    },
    toApproved(row) { // 审核通过
      var _this = this
      this.$confirm('确认通过？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _this.loading = true
        var data = [row]
        approved(data).then(res => {
          Message({
            message: '操作成功',
            type: 'success',
            duration: 2 * 1000
          })
          _this.toQuery()
          _this.loading = false
        }, err => {
          console.log(err)
          _this.loading = false
        })
      })
    },
    toReject(row) { // 审核驳回
      var _this = this
      this.$prompt('驳回原因：', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (value) => {
          if (value === null || value === '') {
            return false
          } else {
            return true
          }
        },
        inputErrorMessage: '请输入驳回原因'
      }).then((val) => {
        console.log('value:' + JSON.stringify(val))
        _this.loading = true
        var data = [row]
        reject({ listInfos: data, rejectRemark: val.value }).then(res => {
          Message({
            message: '操作成功',
            type: 'success',
            duration: 2 * 1000
          })
          _this.toQuery()
          _this.loading = false
        }, err => {
          console.log(err)
          _this.loading = false
        })
      })
    },
    toMultipleApproved() { // 审核通过
      if (this.checkedRows == null || this.checkedRows.length <= 0) {
        Message({
          message: '请选择需要审核的记录',
          type: 'warning',
          duration: 2 * 1000
        })
        return
      }
      var _this = this
      this.$confirm('确认通过？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _this.loading = true
        var data = _this.checkedRows
        approved(data).then(res => {
          Message({
            message: '操作成功',
            type: 'success',
            duration: 2 * 1000
          })
          _this.toQuery()
          _this.loading = false
        }, err => {
          console.log(err)
          _this.loading = false
        })
      })
    },
    toMultipleReject() { // 审核驳回
      if (this.checkedRows == null || this.checkedRows.length <= 0) {
        Message({
          message: '请选择需要审核的记录',
          type: 'warning',
          duration: 2 * 1000
        })
        return
      }
      var _this = this
      this.$prompt('驳回原因：', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (value) => {
          if (value === null || value === '') {
            return false
          } else {
            return true
          }
        },
        inputErrorMessage: '请输入驳回原因'
      }).then((val) => {
        console.log('value:' + JSON.stringify(val))
        this.loading = true
        var data = _this.checkedRows
        reject({ listInfos: data, rejectRemark: val.value }).then(res => {
          Message({
            message: '操作成功',
            type: 'success',
            duration: 2 * 1000
          })
          _this.toQuery()
          _this.loading = false
        }, err => {
          console.log(err)
          _this.loading = false
        })
      })
    },
    toConfirm() { // 终审
      var _this = this
      this.$confirm('确认终审？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _this.loading = true
        var data = { scheduleId: _this.$refs.scheduleHeader.schedule.id }
        confirm(data).then(res => {
          Message({
            message: '操作成功',
            type: 'success',
            duration: 2 * 1000
          })
          _this.loading = false
          _this.$refs.scheduleHeader.loadSchedule() // 重新加载档期
          _this.toQuery()
        }, err => {
          console.log(err)
          _this.loading = false
        })
      })
    },
    toDowndload() { // 下载清单
      var _this = this
      this.$confirm('确认下载？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _this.loading = true
        var data = { scheduleId: this.$refs.scheduleHeader.schedule.id }
        doDownload('/olm-excel/excel/exportOlmListData', data, '清单文件.xlsx').then(_ => {
          _this.loading = false
        }, error => {
          console.log(error)
          _this.loading = false
        })
      })
    },
    toDowndloadStoreUpc() { // 下载门店UPC
      var _this = this
      this.$confirm('确认下载？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _this.loading = true
        var data = { scheduleId: this.$refs.scheduleHeader.schedule.id }
        doDownload('/olm-excel/excel/exportOlmListStoreData', data, '门店UPC清单.zip').then(_ => {
          _this.loading = false
        }, error => {
          console.log(error)
          _this.loading = false
        })
      })
    },
    toAnalysisAll() { // 按档期分析（）
      console.log('toAnalysisAll')
      var analysisList = this.$refs.analysisList
      analysisList.schedules = this.$refs.scheduleHeader.schedules
      analysisList.schedule = this.$refs.scheduleHeader.schedule
      if (analysisList.schedule.scheduleGroup && analysisList.schedule.scheduleGroup === 2) {
        Message({
          message: '临时档期，暂不支持分析功能',
          type: 'warning',
          duration: 2 * 1000
        })
        return
      }
      analysisList.totalUrl = '/queryListAnalysisDataNoRole'
      analysisList.deptUrl = '/queryDeptListAnalysisInfoNoRole'
      analysisList.type = 2
      analysisList.dialog = true
    },
    toAnalysis(entity) { // 按采购，档期分析
      console.log('toAnalysis')
      var analysisList = this.$refs.analysisList
      analysisList.schedules = this.$refs.scheduleHeader.schedules
      analysisList.schedule = this.$refs.scheduleHeader.schedule
      if (analysisList.schedule.scheduleGroup && analysisList.schedule.scheduleGroup === 2) {
        Message({
          message: '临时档期，暂不支持分析功能',
          type: 'warning',
          duration: 2 * 1000
        })
        return
      }
      analysisList.totalUrl = '/queryListAnalysisDataNoRole'
      analysisList.deptUrl = '/queryDeptListAnalysisInfoNoRole'
      analysisList.buyerIds = this.buyerIds
      analysisList.type = 1
      analysisList.oldEntity.buyerIds = [entity.buyerId]
      analysisList.dialog = true
    },
    showAnalysisList(val) {
      var analysisList = this.$refs.analysisList

      analysisList.dialog = true
    },
    toDelete(val) { // 删除
      var _this = this
      this.$confirm('确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _this.loading = true
        deleteScheduleBuyer(val).then(res => {
          if (res) {
            Message({
              message: res.result,
              type: 'success',
              duration: 2 * 1000
            })
            _this.toQuery()
          }
          _this.loading = false
        }, err => {
          _this.loading = false
          console.log(err)
        })
      })
    }
  }
}
</script>
<style scoped>
 .head-context >>> .el-form-item--mini.el-form-item {
   margin-bottom: 0px;
   padding-bottom: 0px;
 }
.list-operation >>> .el-divider--vertical {
  margin: 0 2px
}
</style>
